//
//  MyHelper.m
//  录音
//
//  Created by user on 16/6/13.
//  Copyright © 2016年 jingyi. All rights reserved.
//

#import "MyHelper.h"
#import "VoiceConverter.h"

@implementation MyHelper

/**
 *  获取文件路径
 *
 *  @param fileName 文件名
 *  @param type     后缀, 类型
 *
 *  @return 路径字符串
 */
+ (NSString *)getPathByFileName:(NSString *)fileName
                         ofType:(NSString *)type
{
    NSString *doc           = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0];
    NSString *fileDirectory = [[doc stringByAppendingPathComponent:fileName]stringByAppendingPathExtension:type];
    return fileDirectory;
}

/**
    判断文件是否存在
    @param _path 文件路径
    @returns 存在返回yes
 */
+ (BOOL)fileExistsAtPath:(NSString*)path
{
    return [[NSFileManager defaultManager] fileExistsAtPath:path];
}

/**
    删除文件
    @param _path 文件路径
    @returns 成功返回yes
 */
+ (BOOL)deleteFileAtPath:(NSString*)path
{
    return [[NSFileManager defaultManager] removeItemAtPath:path
                                                      error:nil];
}

/**
 *  获取文件大小
 *
 *  @param path 路径
 *
 *  @return size
 */
+ (NSInteger)getFileSize:(NSString*)path{
    NSFileManager * filemanager = [[NSFileManager alloc]init];
    if([filemanager fileExistsAtPath:path]){
        NSDictionary * attributes   = [filemanager attributesOfItemAtPath:path
                                                                    error:nil];
        NSNumber *theFileSize;
        if ( (theFileSize           = [attributes objectForKey:NSFileSize]) )
            return  [theFileSize intValue];
        else
            return -1;
    }
    else{
        return -1;
    }
}

/**
 *  获取录音文件信息
 *
 *  @param filePath    路径
 *  @param fileName    文件名
 *  @param convertTime 转换时间
 */
+ (void)getVoiceFileInfoWithFilePath:(NSString *)filePath
                            fileName:(NSString *)fileName
                         convertTime:(NSTimeInterval)convertTime {
    
    NSInteger size      = [MyHelper getFileSize:filePath]/1024;
    NSLog(@"文件名：%@   文件大小：%ldkb\n", fileName, (long)size);
    NSRange range       = [filePath rangeOfString:@"wav"];
    if (range.length > 0) {
        AVAudioPlayer *play = [[AVAudioPlayer alloc]initWithContentsOfURL:[NSURL URLWithString:filePath]
                                                                    error:nil];
        NSLog(@"文件时长: %.2fs\n", play.duration);
    }
    if (convertTime > 0) {
        NSLog(@"转换时间：%.2fs\n\n", convertTime);
    }
}

/**
 *  获取当前时间戳
 */
+ (NSString *)getCurrentTimeString
{
    NSDateFormatter *dateformat = [[NSDateFormatter  alloc]init];
    [dateformat setDateFormat:@"yyyyMMddHHmmss"];
    return [dateformat stringFromDate:[NSDate date]];
}

/**
 *  wav格式转amr格式
 *
 *  @param originWav 原录音名字
 
 *  @return 转换后的音频名字
 */
+ (NSString *)wavToAmrWithOriginWav:(NSString *)originWav{
    
    NSString *convertAmr;
    if (originWav.length > 0){
        NSDate *date = [NSDate date];
        convertAmr   = [originWav stringByAppendingString:@"wavToAmr"];
        //转格式
         [VoiceConverter ConvertWavToAmr:[self getPathByFileName:originWav ofType:@"wav"]
                             amrSavePath:[self getPathByFileName:convertAmr ofType:@"amr"]];
        
        [self getVoiceFileInfoWithFilePath:[self getPathByFileName:convertAmr ofType:@"amr"]
                                  fileName:convertAmr
                               convertTime:[[NSDate date] timeIntervalSinceDate:date]];
    }
    return convertAmr;
}

/**
 *  amr转wav格式
 *
 *  @param originWav  原音频名字
 *  @param convertAmr 转换为amr后名字
 *
 *  @return 转换为wav后的音频名字
 */
+ (NSString *)amrToWavWithOriginAmr:(NSString *)originAmr {
    
    NSString *convertWav;
    if (originAmr.length > 0){
        NSDate *date = [NSDate date];
        convertWav   = [originAmr stringByAppendingString:@"amrToWav"];
        //转格式
        [VoiceConverter ConvertAmrToWav:[MyHelper getPathByFileName:originAmr ofType:@"amr"]
                            wavSavePath:[MyHelper getPathByFileName:convertWav ofType:@"wav"]];
        [MyHelper getVoiceFileInfoWithFilePath:[MyHelper getPathByFileName:convertWav ofType:@"wav"]
                                      fileName:convertWav
                                   convertTime:[[NSDate date] timeIntervalSinceDate:date]];
    }
    return convertWav;
}


#pragma mark - 字典->json字符串 -
+ (NSString *)dictionaryToJson:(NSDictionary *)dic {
    
    NSError *parseError = nil;
    //字典转data
    NSData *data = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError];
    return [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]; //data转json
}

#pragma mark - json字符串->字典 -
+ (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString {
    
    if (jsonString == nil) {
        
        return nil;
    }
    //json转data
    NSData *jsonData  = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    //json解析
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                         
                                                        options:NSJSONReadingMutableContainers
                         
                                                          error:&err];
    
    if(err) {
        
        NSLog(@"json解析失败啦啦：%@",err);
        
        return nil;
    }
    return dic;
}

/**
 *   创建AVAudioSession
 */
+ (AVAudioSession *)initAVAudioSession {
    
    //让设备开启录音模式
    AVAudioSession *session = [AVAudioSession sharedInstance];
    NSError *sessionError;
    [session setCategory:AVAudioSessionCategoryPlayAndRecord error:&sessionError];
    if (session) {
        [session setActive:YES error:nil];//启动音频会话管理,此时会阻断后台音乐的播放.
    } else {
        NSLog(@"Error creating session: %@", [sessionError description]);
    }
    return session;
}

@end
